package ltd.hxya.novel.springsecurity.utils;

import ltd.hxya.novel.springsecurity.entity.UserDetail;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class SecurityUtils {

    /**
     * 获得直接转成UserDetail对象的方法
     * @return
     */
    public static UserDetail principal(){
        return (UserDetail) authentication().getPrincipal();
    }

    /**
     * 获得原生的返回Object的方法
     * @return
     */
    public static Object principalObject(){
        return authentication().getPrincipal();
    }

    /**
     * 获得Authentication
     * @return
     */
    public static Authentication authentication(){
        return getSecurityContext().getAuthentication();
    }

    /**
     * 获得SecurityContext
     * @return
     */
    public static SecurityContext getSecurityContext(){
        return SecurityContextHolder.getContext();
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
}
